<?php

namespace Fendx\Middleware;

use Fendx\Config;
use Fendx\Core\RequestContext;
use Fendx\Di;
use Fendx\Exception\AccessDeniedException;
use Fendx\Exception\ExitException;
use Fendx\Funcs\FendxArray;
use Fendx\Logger;
use Fendx\Router\Middleware\MiddlewareInterface;
use Fendx\Router\Middleware\RequestHandler;
use Fendx\Tools\AuthToken;

class AuthorizationMiddleware implements MiddlewareInterface
{

    public function process($request, RequestHandler $handler)
    {
        $request = Di::factory()->getRequest();

        $options = $request->getOptions();
        $config = [];
        $isLogin = true;
        foreach ($options as $option) {
            // 关闭JWT
            if (0 === strcmp($option, 'oauth=off')) {
                $config = [];
                $isLogin = false;
                break;
            }else if (str_starts_with($option, 'oauth=')) {
                $config = Config::get(sprintf('Fendx.oauth.%s', substr($option, 6)));
            }
        }
        if ($isLogin && !empty($config)) {
            $token = $request->header('AUTHORIZATION');
            if (empty($token)) {
                throw new AccessDeniedException('用户未登录');
            }

            $token = str_replace('Bearer ', '', $token);

            // 解析token
            $authToken = new AuthToken();
            $authToken->setSecret($config['key']);
            $userInfo = $authToken->parse($token);
            RequestContext::set("__user", $userInfo);
        }

        $result = $handler->handle($request);

        return $result;
    }
}
